/**
 * @Author :sunwei
 * @Description:
 * @Date create in 19:12  2021/5/23
 * @Modified by:
 * <p>
 * 将任务线程作为守护线程执行,并且join到主线程,如果超过时间直接中断主线程,守护线程自然也结束了.
 */
public class ThreadCloseForce {
    private Thread master;
    private volatile boolean finished = false;

    public void start(Runnable task, long mills) {
        master = new Thread(() -> {
            Thread worker = new Thread(task);
            worker.setDaemon(true);
            worker.start();

            try {
                worker.join();
                finished = !finished;
            } catch (InterruptedException e) {
                System.out.println("catch a InterruptedException,time out ");
            }

        });

        master.start();
        //守护线程需要等待所有非守护线程结束才会结束,所以这里是有问题的.
        shutdown(mills);

        Thread deadLoop = new Thread(()->{
            while(true){
                try {
                    Thread.sleep(11000);
                } catch (InterruptedException e) {
                    System.out.println("deadLoop InterruptedException");
                }
            }
        });

        deadLoop.start();
    }

    public void shutdown(long mills) {
        long start = System.currentTimeMillis();

        while (!finished) {
            long end = System.currentTimeMillis();
            if ((end - start) > mills) {
                System.out.println("time out ,will shutdown the master");
                master.interrupt();
                finished = !finished;
            }
            try {
                master.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
